(function($) {
    $.fn.extend({
        insertAtCaret: function(myValue) {
            var $t = $(this)[0];
              //IE
            if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            } else
            //!IE
            if ($t.selectionStart || $t.selectionStart == "0") {
                var startPos = $t.selectionStart;
                var endPos = $t.selectionEnd;
                var scrollTop = $t.scrollTop;
                $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
                this.focus();
                $t.selectionStart = startPos + myValue.length;
                $t.selectionEnd = startPos + myValue.length;
                $t.scrollTop = scrollTop;
            } else {
                this.value += myValue;
                this.focus();
            }
        }
    })
})(jQuery);

var ShopsFace = {
    icons :  [
        ["色","se.png"],
        ["开心","kaixin.png"],
        ["无语","wuyu.png"],
        ["闭嘴","bizui.png"],

        ["呲牙","ciya.png"],
        ["笑哭","xiaoku.png"],
        ["惊讶","jingya.png"],
        ["大笑","daxiao.png"],

        ["白眼","baiyan.png"],
        ["惊恐","jingkong.png"],
        ["大哭","daku.png"],
        
        ["飞吻","feiwen.png"],
        ["坏笑","huaixiao.png"],
        ["流鼻血","liubixue.png"],        
        ["流汗","liuhan.png"],
        
        ["懵逼","mengbi.png"],
        ["生气","shengqi.png"],        
        ["受伤","shoushang.png"],
        ["衰","shuai.png"],
        
        ["贪吃","tanchi.png"],
        ["吐舌头","tushetou.png"],        
        ["笑脸","xiaolian.png"],
        ["又死了","yousile.png"],
    ],
    config  : {
        faceListId: "#face",
        iconPath: "./icons/",
        inputId: "#text"
    },
    init: function(obj){
        var that = this;
        $.extend(that.config, obj);
        $.each(that.icons,function(i,e){
            var name = e[0];
            var path = that.config.iconPath + e[1];
            var img = $('<img alt="'+name+'" title="'+name+'" src="'+path+'"/>')
            $(that.config.faceListId).append(img)
        })

        $(document).on('click',that.config.faceListId + " img",function(){
            var name=  $(this).attr("alt")
            var inputName = "[" + name  + "]";
            $(that.config.inputId).insertAtCaret(inputName);
        })

    },
    replaceFace : function(content){
        var that = this;
        $.each(that.icons,function(i,e){
           var name = e[0];
           var path = that.config.iconPath + e[1];
           content = content.replace(new RegExp('\\['+name+'\\]','g'),'<img src="'+path+'" class="face" />');
        })
        return content;
    }
}
